package com.controller;

import com.bean.Seat;
import com.bean.SeatLog;
import com.exception.ErrorCodeEnum;
import com.exception.GlobalExceptionResolver;
import com.service.SeatLogService;
import com.service.SeatService;
import com.utils.NetworkUtil;
import com.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

@Controller
public class SeatController {
    Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    @Autowired
    SeatService seatService;

    @Autowired
    SeatLogService seatLogService;

    @RequestMapping(value = {"/", "/index.html"})
    public String list(Model model, HttpSession session) {
        List<Seat> seatList = seatService.list();
        List<List<Seat>> lists = new ArrayList<List<Seat>>();
        int i = 0;
        List<Seat> temp = new ArrayList<>();
        for (Seat seat : seatList) {
            temp.add(seat);
            if (++i == 8) {
                lists.add(temp);
                temp = new ArrayList<>();
                i = 0;
            }
        }
        if (seatList.size() % 8 != 0) {
            lists.add(temp);
        }
        SeatLog seatUser = (SeatLog) session.getAttribute("seatUser");
        if (seatUser != null) {
            long lastAccessedTime = session.getLastAccessedTime();//时间戳 单位毫秒
            int maxInactiveInterval = session.getMaxInactiveInterval(); //单位秒
            lastAccessedTime = lastAccessedTime + maxInactiveInterval * 1000;
            Date date = new Date(lastAccessedTime);
            model.addAttribute("endTime", date);
        }
        model.addAttribute("tempList", lists);
        return "main";
    }

    @ResponseBody
    @RequestMapping(value = "/processServlet", produces = "application/json;charset=utf-8")
    public R process(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "data") String seatName, String userName, @RequestParam(required = false, defaultValue = "2") Integer useTime) {
        SeatLog seatUser = (SeatLog) request.getSession().getAttribute("seatUser");
        if (seatUser != null) {
            return R.error(ErrorCodeEnum.SEAT_SELECTION_REPEAT.getCode(), ErrorCodeEnum.SEAT_SELECTION_REPEAT.getMsg());
        }
//        String userName = "userName-" + UUID.randomUUID().toString().substring(0, 5);

        try {
            seatUser = seatService.selected(seatName, userName);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        if (seatUser != null) {
            HttpSession session = request.getSession();
            session.setAttribute("seatUser", seatUser);
            useTime = useTime > 6 ? 6 : useTime;
            session.setMaxInactiveInterval(60 * 60 * useTime); //2小时过期
            String id = session.getId();
            Cookie cookie = new Cookie("JSESSIONID", id);
            cookie.setMaxAge(60 * 60 * 24 * 365); //1年过期
            response.addCookie(cookie);
            return R.ok();
        }
        return R.error(ErrorCodeEnum.SEAT_SELECTION_FAILED.getCode(), ErrorCodeEnum.SEAT_SELECTION_FAILED.getMsg());
    }


    @ResponseBody
    @RequestMapping(value = "/exit", produces = "application/json;charset=utf-8")
    public R exit(HttpServletRequest request, HttpServletResponse response) {

        SeatLog seatUser = (SeatLog) request.getSession().getAttribute("seatUser");
        if (seatUser == null) {
            return R.error(ErrorCodeEnum.CANNOT_LOG_OUT_WITHOUT_SELECTION.getCode(), ErrorCodeEnum.CANNOT_LOG_OUT_WITHOUT_SELECTION.getMsg());
        }
        try {
            seatUser.setIp(NetworkUtil.getIpAddress(request));
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        boolean flag = seatService.exit(seatUser);
        if (flag) {
            request.getSession().setMaxInactiveInterval(1);
            request.getSession().removeAttribute("seatUser");
            return R.ok();
        }
        return R.error(ErrorCodeEnum.UNKNOWN_ABNORMAL_EXIT_FAILED.getCode(), ErrorCodeEnum.UNKNOWN_ABNORMAL_EXIT_FAILED.getMsg());
    }


    public void getSessions(final HttpServletRequest request) {
        final HttpSession httpSession = request.getSession();
        Enumeration<String> attrs = httpSession.getAttributeNames();

        while (attrs.hasMoreElements()) {
            // 获取session键值
            String name = attrs.nextElement().toString();
            // 根据键值取session中的值
            Object vakue = httpSession.getAttribute(name);
            // 打印结果
            System.out.println("------" + name + ":" + vakue + "--------\n");
        }
        return;

    }

}
